package info.batcloud.fanli.api.controller;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@RestController("/test")
@RequestMapping("/test")
public class TestController {

    @GetMapping("/download")
    public Object download() throws IOException {
        String requestHeader = "Accept: */*\n" +
                "Accept-Encoding: gzip, deflate, br\n" +
                "Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7\n" +
                "Connection: keep-alive\n" +
                "Content-Length: 3123\n" +
                "Content-Type: application/json; charset=UTF-8\n" +
                "Cookie: xhsTrackerId=106f9508-5ef6-4965-c915-2be5fe1cb30d; extra_exp_ids=m_loadMoreNote-exp1; Hm_lvt_d0ae755ac51e3c5ff9b1596b0c09c826=1527219821; Hm_lpvt_d0ae755ac51e3c5ff9b1596b0c09c826=1527219884; beaker.session.id=edf274d3e63fc6c48bd3512dce3dbb01026b5fc3gAJ9cQEoVQhfZXhwaXJlc3ECY2RhdGV0aW1lCmRhdGV0aW1lCnEDVQoH4gYBAywtAN7zhVJxBFUDX2lkcQVVIDVjMzQyNzdlZjQyYTRlM2ZiNGQzZDM2ODgxNGJjZWY3cQZVDl9hY2Nlc3NlZF90aW1lcQdHQdbB4atDr1dVDl9jcmVhdGlvbl90aW1lcQhHQdbB4Zq5yB11Lg==\n" +
                "Host: t.xiaohongshu.com\n" +
                "Origin: https://www.xiaohongshu.com\n" +
                "Referer: https://www.xiaohongshu.com/discovery/item/5b025609304b14499e63a0df\n" +
                "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36";
        HttpGet httpGet = new HttpGet("http://sa.xiaohongshu.com/lsF-V4hc0ve741ob4luzgVXhjVTj_compress_L2");
        HttpClient httpClient = HttpClientBuilder.create().build();
        for (String s : requestHeader.split("\n")) {
            int keyIdx = s.indexOf(":");
            httpGet.addHeader(s.substring(0, keyIdx), s.substring(keyIdx + 1));
        }
        HttpResponse response = httpClient.execute(httpGet);
        File file = new File("~/aa11.mp4");
        if (!file.exists()) {
            file.delete();
        }
        OutputStream os = new FileOutputStream(file);
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流保存到本地文件

        // 开始读取
        while ((len = response.getEntity().getContent().read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        os.close();
        return 1;
    }

}
